import re
import time
import random
import datetime as dt
from urllib.parse import quote

import requests
import redis
from pyquery import PyQuery
from gevent import monkey
from gevent.pool import Pool
from loguru import logger

from decrypt import decrypt

monkey.patch_socket()
_coroutine_pool = Pool()
redis_cli = redis.Redis()


def get_ip():
    params = {
        'apikey': '9eceff6b6002ffb5defcca8d8f6b00d52f53871e',
        'num': 20,
        'type': 'json',
        'line': 'win',
        'proxy_type': 'secret'
    }
    resp = requests.get('https://www.7yip.cn/api/', params=params)
    return resp.json()


def get_uid():
    success_uid_list = redis_cli.smembers('success_uid')
    uid_list = []
    while 1:
        uid = random.choice(list(success_uid_list)).decode()
        if redis_cli.exists(uid):
            time.sleep(0.01)
            continue
        uid_list.append(uid)
        if len(uid_list) == 20:
            break
    return uid_list


def start():
    for ip in get_ip():
        uid = get_uid().pop()

        proxies = {
            'http': f'http://{ip}',
            'https': f'https://{ip}'
        }
        _coroutine_pool.apply_async(_request, args=(proxies, uid,))
    _coroutine_pool.join()


@logger.catch
def _request(proxies, uid):
    session = requests.session()
    try:
        resp = session.get('http://httpbin.org/get', proxies=proxies, timeout=3)
    except Exception as e:
        print(e)
    else:
        if resp.ok:
            try:
                do_vote('4396924', uid, session, proxies)
            except Exception as e:
                ...


def captcha_crack(content):
    resp = requests.post("http://127.0.0.1:7788", data=content)
    code = resp.json()["code"]
    return code


def do_vote(listid, uid, session, proxies=None):
    cookies = {
        'D5O_openinfos': quote(quote(f'{{"uid":"{uid}","token":""}}')),
    }

    headers = {
        'Host': 'h5.zhiyyuan.cn',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f2b) NetType/WIFI Language/zh_CN',
        'Accept-Language': 'zh-cn',
        'Refer': 'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
    }

    response = session.get(
        'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
        headers=headers,
        cookies=cookies,
        proxies=proxies,
        timeout=10)

    html = response.text
    # print(html)
    # print(response.ok)
    tokenVal = re.findall("tokenVal='(.*?)'", html)
    print(tokenVal)
    if not tokenVal:
        return
    if tokenVal[0] == '':
        return
    if dt.datetime.now().minute == 00 or dt.datetime.now().minute == 30:
        if redis_cli.sadd('vote_time', dt.datetime.now().strftime('%Y-%m-%d %H:%M:00')):
            doc = PyQuery(html)
            redis_cli.hset('votes_hd', f'{dt.datetime.now()}', f'{doc(".x_4397421").text()}')
            redis_cli.hset('votes_hy', f'{dt.datetime.now()}', f'{doc(".x_4396924").text()}')
            redis_cli.hset('votes_sg', f'{dt.datetime.now()}', f'{doc(".x_4735510").text()}')

    ouidVal = re.findall("ouidVal='(.*?)'", html)
    while 1:
        brandid = '1902857'
        idnum = brandid + listid
        zheng = ''
        idlength = 20 - len(idnum)

        for _ in range(idlength):
            zheng += str(round(random.random() * 9))

        rnd = f'{brandid}{listid}{zheng}'

        captcha_url = f'https://v.tiantianvote.com/api/c2/captchas.png.php?rnd={rnd}&type=2&id={listid}'

        # time.sleep(1)
        resp = session.get(captcha_url, proxies=proxies, timeout=10)
        # print(resp.ok)
        with open('vote.jpg', 'wb') as f:
            f.write(resp.content)
        pic_str = captcha_crack(resp.content)

        # captcha = input('输入验证码')

        captcha = (decrypt(pic_str)).strip()

        data = {
            'captcha': captcha,
            'rnd': rnd,
            'type': 2,
            'id': listid,
        }
        time.sleep(1)
        resp = session.post('https://v.tiantianvote.com/api/c2/captchas.check1.php', data=data, proxies=proxies,
                            timeout=10)
        print(resp.text)
        if re.search('﻿{"status":200,', resp.text):
            # print(captcha)
            break
        else:
            # time.sleep(random.randint(10, 60) * random.random())
            continue

    # print(captcha)
    data = {
        'brandid': brandid,
        'itemid': listid,
        'yqm': captcha,
        'rnd': rnd,
        'token': tokenVal[0],
        'ouid': uid,
        'sid': '0cf703fcd4add7d4',
    }
    time.sleep(1)

    headers_p = {
        'Host': 'v.tiantianvote.com',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Origin': 'https://h5.zhiyyuan.cn',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f2b) NetType/WIFI Language/zh_CN',
        'Referer': 'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
        'Accept-Language': 'zh-cn',
    }

    resp = requests.post('https://v.tiantianvote.com/v.php', data=data, headers=headers_p, proxies=proxies, timeout=10)
    print(resp.text)
    if re.search('"code":1,"msg":"success"', resp.text):
        redis_cli.sadd('success_uid', uid)
        redis_cli.set(uid, 1, ex=1800)

    if re.search('{"code":11,"msg"', resp.text):
        redis_cli.srem('success_uid', uid)
    if re.search('{"code":6,"msg"', resp.text):
        ...
    return


if __name__ == '__main__':
    while 1:
        s = time.time()
        start()
        e = time.time()
        print(e - s)
